import React, { useState } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { colors, spacing, typography } from '../styles/variables';
import { Card, Title, Paragraph, Button, Flex, Grid } from '../styles/components';

// 添加API调用函数
const api = {
  // 获取所有塔罗牌
  getTarotCards: async () => {
    try {
      const response = await fetch('/api/divination/tarot');
      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('获取塔罗牌失败:', error);
      throw error;
    }
  },
  
  // 抽取塔罗牌
  drawTarotCards: async (count) => {
    try {
      const response = await fetch('/api/divination/tarot/draw', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ count }),
      });
      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('抽取塔罗牌失败:', error);
      throw error;
    }
  },
  
  // 解读塔罗牌
  interpretTarotCards: async (cards) => {
    try {
      const response = await fetch('/api/divination/tarot/interpret', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ cards }),
      });
      const data = await response.json();
      return data.data;
    } catch (error) {
      console.error('解读塔罗牌失败:', error);
      throw error;
    }
  }
};

const TarotHeader = styled.div`
  text-align: center;
  padding: ${spacing.xl} 0;
  margin-bottom: ${spacing.xl};
`;

const SpreadSelector = styled.div`
  display: flex;
  justify-content: center;
  gap: ${spacing.md};
  margin: ${spacing.lg} 0;
  flex-wrap: wrap;
`;

const SpreadButton = styled(Button)`
  background: ${props => props.selected ? colors.gradientGold : colors.backgroundSecondary};
  color: ${props => props.selected ? colors.background : colors.textPrimary};
  border: 1px solid ${props => props.selected ? 'transparent' : colors.border};
`;

const CardsArea = styled.div`
  display: flex;
  justify-content: center;
  gap: ${spacing.lg};
  margin: ${spacing.xxl} 0;
  flex-wrap: wrap;
`;

const TarotCard = styled(motion.div)`
  width: 120px;
  height: 200px;
  perspective: 1000px;
  cursor: pointer;
`;

const CardInner = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
  transition: transform 0.8s;
  transform-style: preserve-3d;
  transform: ${props => props.flipped ? 'rotateY(180deg)' : 'none'};
`;

const CardFront = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  background: ${colors.gradientPurple};
  border-radius: ${spacing.md};
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3rem;
  box-shadow: ${props => props.flipped ? 'none' : '0 10px 25px rgba(0, 0, 0, 0.3)'};
`;

const CardBack = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  background: ${colors.backgroundSecondary};
  border: 2px dashed ${colors.border};
  border-radius: ${spacing.md};
  display: flex;
  align-items: center;
  justify-content: center;
  transform: rotateY(180deg);
  font-size: 3rem;
`;

const ReadingResult = styled(Card)`
  background: linear-gradient(135deg, ${colors.backgroundSecondary} 0%, ${colors.background} 100%);
  margin-top: ${spacing.xxl};
`;

const spreads = [
  { id: 'single', name: '单张牌', description: '快速解答一个问题', count: 1 },
  { id: 'three', name: '三张牌', description: '过去、现在、未来', count: 3 },
  { id: 'celtic', name: '凯尔特十字', description: '全面的命运解读', count: 10 }
];

function TarotReading() {
  const [selectedSpread, setSelectedSpread] = useState('three');
  const [cards, setCards] = useState([]);
  const [flipped, setFlipped] = useState([]);
  const [reading, setReading] = useState(null);
  const [loading, setLoading] = useState(false);

  const startReading = async () => {
    try {
      setLoading(true);
      setReading(null);
      
      // 获取选中的牌阵信息
      const spread = spreads.find(s => s.id === selectedSpread);
      
      // 调用后端API抽取塔罗牌
      const drawnCards = await api.drawTarotCards(spread.count);
      
      // 设置卡片状态
      setCards(drawnCards || []); // 添加默认值检查
      setFlipped(new Array((drawnCards || []).length).fill(false));
    } catch (error) {
      console.error('占卜失败:', error);
      alert('占卜失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const flipCard = (index) => {
    setFlipped(prev => {
      const newFlipped = [...prev];
      newFlipped[index] = !newFlipped[index];
      return newFlipped;
    });
  };

  // 当所有卡片都被翻开时，获取解读
  React.useEffect(() => {
    const getAllFlipped = () => flipped && flipped.every(f => f);
    
    if (cards && cards.length > 0 && getAllFlipped() && !reading) {
      getReading();
    }
  }, [flipped, cards, reading]);

  const getReading = async () => {
    try {
      setLoading(true);
      
      // 调用后端API解读塔罗牌
      const interpretation = await api.interpretTarotCards(cards || []); // 添加默认值检查
      
      // 设置解读结果
      setReading(interpretation);
    } catch (error) {
      console.error('获取解读失败:', error);
      alert('获取解读失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <TarotHeader>
        <Title>塔罗占卜</Title>
        <Paragraph center>选择牌阵，让塔罗牌为您指引方向</Paragraph>
      </TarotHeader>

      <Card>
        <Paragraph center>选择占卜牌阵</Paragraph>
        <SpreadSelector>
          {spreads.map((spread) => (
            <SpreadButton
              key={spread.id}
              selected={selectedSpread === spread.id}
              onClick={() => setSelectedSpread(spread.id)}
            >
              {spread.name}
            </SpreadButton>
          ))}
        </SpreadSelector>
        
        <Paragraph secondary center>
          {spreads.find(s => s.id === selectedSpread)?.description}
        </Paragraph>
        
        <Flex justify="center" style={{ marginTop: spacing.lg }}>
          <Button variant="primary" onClick={startReading} disabled={loading}>
            {loading ? '占卜中...' : '开始占卜'}
          </Button>
        </Flex>
      </Card>

      {(cards || []).length > 0 && (
        <>
          <CardsArea>
            {(cards || []).map((card, index) => (
              <TarotCard
                key={index}
                onClick={() => flipCard(index)}
                whileHover={{ y: -10 }}
                whileTap={{ scale: 0.95 }}
              >
                <CardInner flipped={flipped[index]}>
                  <CardFront flipped={flipped[index]}>
                    🃏
                  </CardFront>
                  <CardBack>
                    {card.name}
                  </CardBack>
                </CardInner>
              </TarotCard>
            ))}
          </CardsArea>
          
          <Flex justify="center">
            <Button variant="outline" onClick={() => setFlipped(new Array((cards || []).length).fill(true))}>
              全部翻牌
            </Button>
          </Flex>
        </>
      )}

      {reading && (
        <ReadingResult>
          <Title size="md">占卜解读</Title>
          <div style={{ marginBottom: spacing.lg }}>
            <Paragraph>{reading.overall}</Paragraph>
          </div>
          
          {reading && (reading.cards || []).map((card, index) => (
            <div key={index} style={{ marginBottom: spacing.lg }}>
              <h4 style={{ color: colors.textPrimary, marginBottom: spacing.sm }}>
                {card.card} {card.position && `(${card.position})`}
              </h4>
              <Paragraph>{card.interpretation}</Paragraph>
            </div>
          ))}
          
          <Flex justify="center">
            <Button variant="primary">
              🔖 保存解读
            </Button>
          </Flex>
        </ReadingResult>
      )}
    </>
  );
}

export default TarotReading;